package com.ihrm.company.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.company.service.CompanyService;
import com.ihrm.company.service.DepartmentService;
import com.ihrm.company.vo.DeptListVo;
import com.ihrm.domain.company.Company;
import com.ihrm.domain.company.Department;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chahua
 * @date 2022/3/27 11:58
 **/
@CrossOrigin
@RestController
@Api(value = "部门管理增删改查")
@RequestMapping("/company")
public class DepartmentController extends BaseController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private CompanyService companyService;

    @ApiOperation("新增部门")
    @PostMapping("/deparment")
    public Result save(@RequestBody Department department){
        // companyId直接从BaseController中获取
        department.setCompanyId(companyId);
        departmentService.add(department);
        return new Result(ResultCode.SUCCESS);
    }

    @ApiOperation("更新部门")
    @PatchMapping("/department/{id}")
    public Result update(@RequestBody Department department,@PathVariable("id") String id){
        department.setId(id);
        departmentService.update(department);
        return new Result(ResultCode.SUCCESS);
    }

    @ApiOperation("删除部门")
    @DeleteMapping("/department/{id}")
    public Result delete(@PathVariable("id") String id){
        departmentService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    @ApiOperation("根据id查询部门")
    @GetMapping("/department/{id}")
    public Result findById(@PathVariable("id") String id){
        Department department = departmentService.findById(id);
        return new Result(ResultCode.SUCCESS,department);
    }

    @ApiOperation("查询部门列表")
    @GetMapping("/department")
    public Result findAll() throws CommonException {
        Company company = companyService.findById(companyId);
        if(company==null){
            throw new CommonException(ResultCode.COMPANY_IS_NOT_EXIST);
        }
        List<Department> departmentList = departmentService.findAll(companyId);
        DeptListVo deptListVo = new DeptListVo(company, departmentList);
        return new Result(ResultCode.SUCCESS,deptListVo);
    }
}
